/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Practica1Frame.java
 *
 * Created on 15-mar-2011, 17:23:07
 */
package pr3.gui;

import java.awt.BorderLayout;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.math.plot.Plot2DPanel;
import pr3.cruce.CruceCromosomaArbol;
import pr3.mutacion.MutacionArbol;
import pr3.mutacion.MutacionFuncionalSimple;
import pr3.mutacion.MutacionTerminalSimple;

import pr3.seleccion.Ranking;
import pr3.seleccion.Ruleta;
import pr3.seleccion.Torneo;

/**
 * 
 * @author Gonzalo Ortiz Jaureguizar (gortiz at software.imdea.org)
 */
public class Practica3Frame extends javax.swing.JFrame {

    public static final int RULETA = 0;
    public static final int TORNEO = 1;
    public static final int RANKING = 2;
    public static final int MUTACION_ARBOL = 0;
    public static final int MUTACION_FUNCION = 1;
    public static final int MUTACION_TERMINAL = 2;
    public static final int CRUCE_ARBOL = 0;
    double precision = 0.001;
    Plot2DPanel plot;
    AGRunner runner;
    DefaultComboBoxModel seleccionModel;
    DefaultComboBoxModel cruceModel;
    DefaultComboBoxModel mutacionModel;

    /** Creates new form Practica1Frame */
    public Practica3Frame() {
        seleccionModel = new DefaultComboBoxModel();
        seleccionModel.addElement("Ruleta");
        seleccionModel.addElement("Torneo");
        seleccionModel.addElement("Ranking");

        cruceModel = new DefaultComboBoxModel();
        cruceModel.addElement("Cruce simple");

        mutacionModel = new DefaultComboBoxModel();
        mutacionModel.addElement("Arbol");
        mutacionModel.addElement("Función");
        mutacionModel.addElement("Terminales");

        initComponents();

        plot = new Plot2DPanel();
        plot.setLegendOrientation("SOUTH");
        runner = new AGRunner();

        plotPanel.add(plot, BorderLayout.CENTER);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed"
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        calcularButton = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        generacionesSpinner = new javax.swing.JSpinner();
        jLabel8 = new javax.swing.JLabel();
        tamPobSpinner = new javax.swing.JSpinner();
        jLabel6 = new javax.swing.JLabel();
        cruceSpinner = new javax.swing.JSpinner();
        jLabel5 = new javax.swing.JLabel();
        mutacionSpinner = new javax.swing.JSpinner();
        jLabel3 = new javax.swing.JLabel();
        estSeleccionComboBox = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        estCruceComboBox = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        estMutacionComboBox = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        elitismoSpinner = new javax.swing.JSpinner();
        jLabel4 = new javax.swing.JLabel();
        escaladoSpinner = new javax.swing.JSpinner();
        profMinJLabel = new javax.swing.JLabel();
        profMinJSpinner = new javax.swing.JSpinner();
        profMaxJLabel = new javax.swing.JLabel();
        profMaxJSpinner = new javax.swing.JSpinner();
        jPanel2 = new javax.swing.JPanel();
        plotPanel = new javax.swing.JPanel();
        mejorLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Problema del viajante de comercio");

        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel3.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        calcularButton.setText("Recalcular");
        calcularButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                calcularButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(171, Short.MAX_VALUE)
                .addComponent(calcularButton)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(calcularButton)
                .addContainerGap())
        );

        jPanel1.add(jPanel3, java.awt.BorderLayout.PAGE_END);

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Configuracion"));
        jPanel4.setLayout(new java.awt.GridLayout(11, 2, 3, 3));

        jLabel1.setText("Generaciones");
        jPanel4.add(jLabel1);

        generacionesSpinner.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(99), Integer.valueOf(1), null, Integer.valueOf(1)));
        jPanel4.add(generacionesSpinner);

        jLabel8.setText("Tamaño pob");
        jPanel4.add(jLabel8);

        tamPobSpinner.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(100), Integer.valueOf(0), null, Integer.valueOf(1)));
        jPanel4.add(tamPobSpinner);

        jLabel6.setText("Prob cruce (%)");
        jPanel4.add(jLabel6);

        cruceSpinner.setModel(new javax.swing.SpinnerNumberModel(50, 0, 100, 1));
        jPanel4.add(cruceSpinner);

        jLabel5.setText("Prob mutación (%)");
        jPanel4.add(jLabel5);

        mutacionSpinner.setModel(new javax.swing.SpinnerNumberModel(5, 0, 100, 1));
        jPanel4.add(mutacionSpinner);

        jLabel3.setText("Selección");
        jPanel4.add(jLabel3);

        estSeleccionComboBox.setModel(seleccionModel);
        jPanel4.add(estSeleccionComboBox);

        jLabel9.setText("Cruce");
        jPanel4.add(jLabel9);

        estCruceComboBox.setModel(cruceModel);
        jPanel4.add(estCruceComboBox);

        jLabel10.setText("Mutación");
        jPanel4.add(jLabel10);

        estMutacionComboBox.setModel(mutacionModel);
        jPanel4.add(estMutacionComboBox);

        jLabel7.setText("Elitismo (%)");
        jPanel4.add(jLabel7);

        elitismoSpinner.setModel(new javax.swing.SpinnerNumberModel(2, 0, 100, 1));
        jPanel4.add(elitismoSpinner);

        jLabel4.setText("Escalado (%)");
        jPanel4.add(jLabel4);

        escaladoSpinner.setModel(new javax.swing.SpinnerNumberModel(30, 0, 100, 1));
        jPanel4.add(escaladoSpinner);

        profMinJLabel.setText("Prof min");
        jPanel4.add(profMinJLabel);

        profMinJSpinner.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1)));
        jPanel4.add(profMinJSpinner);

        profMaxJLabel.setText("Prof max");
        jPanel4.add(profMaxJLabel);

        profMaxJSpinner.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(10), Integer.valueOf(0), null, Integer.valueOf(1)));
        jPanel4.add(profMaxJSpinner);

        jPanel1.add(jPanel4, java.awt.BorderLayout.NORTH);

        jSplitPane1.setLeftComponent(jPanel1);

        jPanel2.setPreferredSize(new java.awt.Dimension(500, 500));
        jPanel2.setLayout(new java.awt.BorderLayout());

        plotPanel.setLayout(new java.awt.BorderLayout());
        jPanel2.add(plotPanel, java.awt.BorderLayout.CENTER);
        jPanel2.add(mejorLabel, java.awt.BorderLayout.SOUTH);

        jSplitPane1.setRightComponent(jPanel2);

        getContentPane().add(jSplitPane1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void calcularButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_calcularButtonActionPerformed
        int profMin = (Integer) profMinJSpinner.getValue();
        runner.setProfMin(profMin);
        int profMax = (Integer) profMaxJSpinner.getValue();
        runner.setProfMax(profMax);
        
        if(profMax < profMin) {
            JOptionPane.showMessageDialog(
                    this, 
                    "La profundidad máxima no puede ser menor que la mínima", 
                    "Error", 
                    JOptionPane.ERROR_MESSAGE);
            return ;
        }
        
        runner.setGeneraciones((Integer) generacionesSpinner.getValue());
        runner.setPrecision(precision);
        runner.setProbCruce((Integer) cruceSpinner.getValue());
        runner.setProbMutacion((Integer) mutacionSpinner.getValue());
        runner.setTamPoblacion((Integer) tamPobSpinner.getValue());
        runner.setElitismo((Integer) elitismoSpinner.getValue());
        runner.setEscalado((Integer) escaladoSpinner.getValue());
        
        switch (estSeleccionComboBox.getSelectedIndex()) {
            case RULETA:
                runner.setSeleccion(new Ruleta());
                break;
            case TORNEO:
                runner.setSeleccion(new Torneo());
                break;
            case RANKING:
                runner.setSeleccion(new Ranking(2.5d));
                break;
        }
        switch (estCruceComboBox.getSelectedIndex()) {
            case CRUCE_ARBOL:
                runner.setCruce(new CruceCromosomaArbol(profMax));
                break;
        }
        switch (estMutacionComboBox.getSelectedIndex()) {
            case MUTACION_ARBOL:
                runner.setMutacion(new MutacionArbol(profMax));
                break;
            case MUTACION_FUNCION:
                runner.setMutacion(new MutacionFuncionalSimple());
                break;
            case MUTACION_TERMINAL:
                runner.setMutacion(new MutacionTerminalSimple());
                break;
        }

        runner.plot(plot);
        String mejorText = "<html>El mejor individuo es:" + runner.getMejor() + "<br/> y su puntuacion es " + runner.getMejorPuntuacion();
        this.mejorLabel.setText(mejorText);
        System.out.println(runner.getMejor());
    }//GEN-LAST:event_calcularButtonActionPerformed
    public static void setSystemLayout() {
        if (UIManager.getLookAndFeel().getClass().getName().equals("javax.swing.plaf.metal.MetalLookAndFeel")) {
            try {
                final String GTK_LOOK_AND_FEEL = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
                try {
                    if ("Linux".equals(System.getProperty("os.name"))) {
                        UIManager.setLookAndFeel(GTK_LOOK_AND_FEEL);
                    }
                } catch (Exception ex) {
                    Logger.getLogger(Practica3Frame.class.getName()).log(Level.INFO, "Este sistema "
                            + "no acepta el layout de GTK", ex);
                }
                if (!GTK_LOOK_AND_FEEL.equals(UIManager.getLookAndFeel().getClass().getCanonicalName())) {
                    // Set System L&F
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                }
            } catch (UnsupportedLookAndFeelException ex) {
                Logger.getLogger(Practica3Frame.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Practica3Frame.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(Practica3Frame.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(Practica3Frame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String args[]) {

        setSystemLayout();

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Practica3Frame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton calcularButton;
    private javax.swing.JSpinner cruceSpinner;
    private javax.swing.JSpinner elitismoSpinner;
    private javax.swing.JSpinner escaladoSpinner;
    private javax.swing.JComboBox estCruceComboBox;
    private javax.swing.JComboBox estMutacionComboBox;
    private javax.swing.JComboBox estSeleccionComboBox;
    private javax.swing.JSpinner generacionesSpinner;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JLabel mejorLabel;
    private javax.swing.JSpinner mutacionSpinner;
    private javax.swing.JPanel plotPanel;
    private javax.swing.JLabel profMaxJLabel;
    private javax.swing.JSpinner profMaxJSpinner;
    private javax.swing.JLabel profMinJLabel;
    private javax.swing.JSpinner profMinJSpinner;
    private javax.swing.JSpinner tamPobSpinner;
    // End of variables declaration//GEN-END:variables
}
